//
//  CourseListVC.m
//  优学荟管理系统
//
//  Created by 星道 on 17/6/27.
//  Copyright © 2017年 星道三好. All rights reserved.
//

#import "CourseListVC.h"
#import "CourseListCell.h"
#import "CourseListModel.h"
#import "HNCourseEvaluationsVC.h"
#import "AddCourseVC.h"
#import "TeacherCourseSelectView.h"
#import "TeacherCourseSelectModel.h"
#import "HNHandleCourseVC.h"

@interface CourseListVC ()
/**
 当前页码
 */
@property (nonatomic, assign) NSInteger CurrentPage;
/**
 临时页码
 */
@property (nonatomic, assign) NSInteger TempPage;
/**
 数据存放
 */
@property (nonatomic, strong) NSMutableArray *DataArr;
@end

@implementation CourseListVC

- (void)viewDidLoad
{
    [super viewDidLoad];

    self.title = @"课程列表";

    // 配置TableView
    [self SetupTableView];



    self.navigationItem.rightBarButtonItem = self.ID ? nil : [[UIBarButtonItem alloc] initWithTitle:@"添加课程" style:(UIBarButtonItemStyleDone) target:self action:@selector(GoAddCourse)];


}

/** 进入添加课程的VC */
- (void)GoAddCourse
{
    
    HNHandleCourseVC *VC = [[HNHandleCourseVC alloc] init];
    // 声明我这是添加课程
    VC.type = HNHandleCourseTypeAdd;
    VC.PopOfRefresh = ^{
        
        
            [self.tableView.mj_header beginRefreshing];
    };
    [self.navigationController pushViewController:VC animated:YES];
    return;
    
    
    
    
    // 先获取老师的信息
    [self RefreshDataWithTeacher:^(NSArray<TeacherCourseSelectModel *> *Arr) {

        NSMutableArray *TitleArr = [NSMutableArray array];
        [Arr enumerateObjectsUsingBlock:^(TeacherCourseSelectModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            [TitleArr addObject:obj.petName];
        }];
        // 弹窗并选择老师
        TeacherCourseSelectView *View = [TeacherCourseSelectView ConfigWithArr:[TitleArr copy] Complete:^(NSInteger Index) {

            AddCourseVC *VC = [[AddCourseVC alloc] init];
            // 声明我这是增加课程
            VC.mode = AddCourseAdd;
            VC.TeacherID = [Arr[Index] uid];
            VC.RefreshUI = ^{
                [self.tableView.mj_header beginRefreshing];
            };
            [self.navigationController pushViewController:VC animated:YES];
        }];
        View.Title.text = @"请选择课程老师";
    }];
}


- (void)UploadCourse:(NSNumber *)ID {

    HNHandleCourseVC *VC = [[HNHandleCourseVC alloc] init];
    // 声明我这是修改课程
    VC.type = HNHandleCourseTypeEdit;
    // 对应的课程
    VC.Id = ID;
    VC.PopOfRefresh = ^{
        
        [self.tableView.mj_header beginRefreshing];
    };
    [self.navigationController pushViewController:VC animated:YES];
}

#pragma mark  - 配置
/**
 配置TableView
 */
- (void)SetupTableView
{
    // 占位
    self.tableView.tableFooterView = [UIView new];
    self.tableView.tableHeaderView = [UIView new];
    // 预注册
    [self.tableView registerNib:[UINib nibWithNibName:[CourseListCell description] bundle:nil] forCellReuseIdentifier:@"Cell"];
    // 预估高度
    self.tableView.rowHeight = 96;
    //默认页码
    self.CurrentPage = 1;
    // 下拉刷新
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{

        //取当前页码给临时页码
        self.TempPage = self.CurrentPage;
        //设当前页码为1
        self.CurrentPage = 1;
        //请求
        [self RefreshData];
    }];
    //上拉加载
    self.tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{

        //请求
        [self RefreshData];
    }];
    //开始刷新
    [self.tableView.mj_header beginRefreshing];
}


/**
 刷新失败时，判断是否需要从临时页码里取出来给当前页码
 */
- (void)GetPage
{
    if (self.CurrentPage == 1)
    {
        self.CurrentPage = self.TempPage;
    }
}

/**
 结束刷新

 @param Index 0:结束刷新 1:提示没有更多数据 2:tableView数据源更新
 */
- (void)EndRefresh:(NSInteger)Index;
{
    dispatch_async(dispatch_get_main_queue(), ^{
        switch (Index)
        {
            case 0:
            {
                [self.tableView.mj_header endRefreshing];
                [self.tableView.mj_footer endRefreshing];
            }
                break;
            case 1:
            {
                [self.tableView.mj_footer endRefreshingWithNoMoreData];
            }
                break;
            case 2:
            {
                [self.tableView reloadData];
            }
                break;
            default:
                break;
        }
    });
}



#pragma mark - 网络请求
/**
 网络请求
 */
- (void)RefreshData
{


 
    
    [NetManager Get:LLBaseURL(@"yxhUser.do") Auth:YES Params:[self MgrParams] Success:^(id Obj) {

        //结束刷新
        [self EndRefresh:0];
        //判断是否加载成功
        if ([Obj[@"code"] isEqualToNumber:@1000])
        {
            //取值
            NSArray *DataList = Obj[@"t"][@"dataList"];
            //无值时显示没有更多的数据了
            if (DataList.count == 0)
            {
                //显示
                [self EndRefresh:1];
            }
            else
            {
                if (self.CurrentPage == 1)
                {
                    [self.DataArr removeAllObjects];
                }

                //转模型
                [DataList enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {

                    //开始转
                    CourseListModel *Model = [CourseListModel HNObjectValuesForKey:(NSDictionary *)obj];
                    Model.isTaoCan = self.ID ? YES:NO;
                    [self.DataArr addObject:Model];
                }];
                //数据请求成功，页码加1
                self.CurrentPage += 1;
                //通知主线程刷新表单
                [self EndRefresh:2];
            }
        }
        else
        {
            //页码处理
            [self GetPage];
            //显示错误信息
            [MBProgressHUD showError:Obj[@"msg"]];
        }
    } Fail:^(NSError *Error) {

        //结束刷新
        [self EndRefresh:0];
        //页码处理
        [self GetPage];
        //显示错误信息
        [MBProgressHUD showError:NetErr];
    }];
}


- (void)RefreshDataWithTeacher:(void (^)(NSArray <TeacherCourseSelectModel *>*Arr))Complete {

    [MBProgressHUD showHUD];
    NSDictionary *Params = @{
                             @"action":@"getTeacherByOid",
                             @"oid":[AccountTool shareAccountTool].currentAccount.oid
                             };
    [NetManager Get:LLBaseURL(@"lesson.do") Auth:YES Params:Params Success:^(id Obj) {

        if ([Obj[@"code"] isEqualToNumber:@1000]) {

            NSMutableArray *MutableArr = [NSMutableArray array];
            [Obj[@"t"] enumerateObjectsUsingBlock:^(NSDictionary * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {

                [MutableArr addObject:[TeacherCourseSelectModel HNObjectValuesForKey:obj]];
            }];
            dispatch_async(dispatch_get_main_queue(), ^{

                Complete ? Complete ([MutableArr copy]) : nil ;
            });


        } else {
            [MBProgressHUD showError:Obj[@"msg"]];
        }
    } Fail:^(NSError *Error) {
        [MBProgressHUD showError:NetErr];
    }];
}

#pragma mark - TableView代理
//区
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

//行
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.DataArr.count;
}

//Cell
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    //取模型
    CourseListModel *Model = self.DataArr[indexPath.row];
    //实例Cell
    CourseListCell *Cell = [tableView dequeueReusableCellWithIdentifier:@"Cell" forIndexPath:indexPath];
    //调用点语法
    Cell.Model = Model;
    [Cell.upButton addTarget:self action:@selector(upButtonAction:) forControlEvents:(UIControlEventTouchUpInside)];
    
    return Cell;
}

//点击
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
//    // 取值
//    CourseListModel *Model = self.DataArr[indexPath.row];
//    //实例
//    HNCourseEvaluationsVC *VC = [[HNCourseEvaluationsVC alloc] init];
//    //传ID
//    VC.ID = [Model.ID stringValue];
//
//    // 这个值是根据本级界面课程列表的ID而来，ID值为nil时IsTaoCanLieBiao为NO,否则为YES
//    //这个是字段的作用是区分网终请求action值
//    VC.IsTaoCanLieBiao = self.ID == nil ? NO : YES;
//    [self.navigationController pushViewController:VC animated:YES];
}



#pragma mark - 处理方法
/**
 根据self.ID是否有值判断
 */
- (NSDictionary *)MgrParams
{
    //课程列表
    if (self.ID == nil)
    {
        NSDictionary *Params = @{
                                 @"action"      :@"getLessonList",
                                 @"pageNumber"  :@(self.CurrentPage),
                                 @"oid"         :[AccountTool shareAccountTool].currentAccount.oid
                                 };
        return Params;
    }

    //套餐列表->课程列表
    else
    {
        NSDictionary *Params = @{
                                 @"action"      :@"coursePackageOrderdetail",
                                 @"pageNumber"  :@(self.CurrentPage),
                                 @"packageId"   :self.ID,
                                 @"oid"         :[AccountTool shareAccountTool].currentAccount.oid
                                 };
        return Params;
    }
}

- (void)upButtonAction:(UIButton *)sender{
    
    CourseListCell *cell = (CourseListCell *)sender.superview.superview;
    NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
    CourseListModel *model = self.DataArr[indexPath.row];
    
    if (0 == [model.sellStatus integerValue]) {
        
        [self netWorkOneId:[NSString stringWithFormat:@"%@",model.ID] sellStatus:@"1"];
        
    }else if (1 == [model.sellStatus integerValue]){
         [self netWorkOneId:[NSString stringWithFormat:@"%@",model.ID] sellStatus:@"0"];
        
    }
    
    
    
    
}

#pragma mark --- 上架下架
- (void)netWorkOneId:(NSString *)Id sellStatus:(NSString *)sellStatus{
   
    NSString *url = [NSString stringWithFormat:@"lesson.do?action=changeSellStatus&id=%@&sellStatus=%@",Id,sellStatus];
    
    NSLog(@"%@ %@",LLBaseURL(url),[AccountTool shareAccountTool].currentAccount.authCode);
    
    [NetManager Get:LLBaseURL(url) Auth:YES Params:nil Success:^(id Obj) {
        

        [Obj[@"code"] isEqualToNumber:@1000] ? [self.tableView.mj_header beginRefreshing]:[HUD showError:Obj[@"msg"]];
        
        
    } Fail:^(NSError *Error) {
        [HUD showError:NetErr];
    }];
    
    
    
}






#pragma mark - Setter
- (NSMutableArray *)DataArr
{
    if (!_DataArr)
    {
        _DataArr = [NSMutableArray array];
    }
    return _DataArr;
}


@end
